<?php
namespace App\Http\Controllers;
/**
 * 
 * 购物车控制器
 * 
 * @author maqu
 *
 */

use App\Services\GoodsService;
use App\Services\LogisticsService;
use App\Services\OrderPingppService;
use App\Services\OrderService;
use App\Services\StoreService;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\DB;
class CashierController extends BaseController {

    //可使用优惠券列表
//    public function listCoupon(){
//
//        $user_id = Input::get('user_id');
//        $amount=intval(Input::get('amount',0));//购物金额
//        $firstRow = Input::get('firstrow',0);
//        $pageSize = Input::get('pagesize',10);
//
//        $couponService = new CouponService();
//
//        $user_coupons=$couponService->getCashierCouponList($user_id,$amount,$firstRow,$pageSize);
//
//        return $this->success($user_coupons);
//    }

    //可使用配送方式列表
//    public function listShipping(){
//
//        $store_id = Input::get('stoer_id',1);
//        $firstRow = Input::get('firstrow',0);
//        $pageSize = Input::get('pagesize',10);
//
//        $cashierService = new CashierService();
//
//        /* 配送方式 */
//        $shippingList = $cashierService->getShippingList($store_id,$firstRow,$pageSize);
//        if (empty($shippingList))
//        {
//            return $this->failure ( '没有配送方式' );
//        }
//
//        return $this->success($shippingList);
//    }

//	public function initByCart(){
//
//		$user_id = Input::get('user_id');
//        $store_id = Input::get('store_id',1);
//
//        if(!$user_id){
//            return $this->args_invalid();
//        }
//
//        $userinfo = DB::table('member')->where('user_id',$user_id)->first();
//        if(!$userinfo){
//            return $this->failure("用户不存在");
//        }
//
//        if(empty($userinfo->user_name)){
//            return $this->need_bind();
//        }
//
//        $cashierService = new CashierService();
//
//        //获取购物信息
//		if(!Input::has('rec_ids')){//整个购物车购买
//	        $carts = $cashierService->getGoodsByCart($user_id,$store_id);
//	    }else{//购物车内部分购买
//	    	$rec_id_list=explode(",",Input::get('rec_ids'));
//
//            //判断购物车信息是否发生变化
//            $cartService = new CartService();
//            $cart = $cartService->getCartList($rec_id_list,$user_id);
//            if(count($cart) != count($rec_id_list)){
//                return $this->failure ( '购物车信息已发生改变' );
//            }
//            $carts = $cashierService->getGoodsByCart($user_id,$store_id,$rec_id_list);
//	    }
//
//        if(empty($carts)){
//            return $this->failure ( '购物车内没有商品' );
//        }
//
//        //编辑返回数据
//        $return = $carts;
//        $return['selected_rec_ids']=Input::get('rec_ids');
//        //获取默认地址
//        $address= DB::table('address')->where('user_id',$user_id)->where('is_default',1)->first();
//
//        if($address){
//		  $return['default_address'] = (array)$address;
//        }else {
//            $return['default_address'] = [];
//        }
//
////        /* 默认配送方式 */
////        $shipping_methods = $cashierService->getShippingMethods($store_id);
////        $return['default_shipping']          = $shipping_methods;
////
////        /* 配送费用=首件费用＋超出的件数*续件费用 */
////        if($shipping_methods){
////            $shipping_fee = $shipping_methods->first_price + ($carts['total_store']['quantity'] - 1) * $shipping_methods->step_price;
////        }else{
////            $shipping_fee = 0;
////        }
////        $return['default_shipping']->shipping_fee        = $shipping_fee;
//
//        //获取店铺配置
//        $storeService = new StoreService();
//        $storeConfig = $storeService->getStoreConfig($carts['store_info']['store_id']);
//
//        /* 配送费为固定设置 */
//        if($carts['total_store']['goods_amount'] < $storeConfig['shipping']['min_free']){
//            $shipping_fee = $storeConfig['shipping']['shipping_fee'];
//        }else{
//            $shipping_fee = 0;
//        }
//        $return['shipping_fee'] = $shipping_fee;
//
//        /* 默认使用快要过期的可用优惠券 */
//        $couponService = new CouponService();
//        $user_coupon=$couponService->getCashierCouponMethods($user_id,$carts['total_store']['goods_amount']);
//        $return['default_coupon'] = $user_coupon;
//        if($user_coupon){
//            $coupon_fee = $user_coupon['coupon_value'];
//        }else{
//            $coupon_fee = 0;
//        }
//
//        $return['sub_amount'] = $carts['total_store']['goods_amount'] + $shipping_fee - $coupon_fee;
//
//        //支付方式列表
//        $pay_list = [
//            [
//                'payment_id'   => 1,
//                'payment_name' => '支付宝',
//                'payment_code' => 'alipay'
//            ],
//            [
//                'payment_id'   => 2,
//                'payment_name' => '微信',
//                'payment_code' => 'wxPay'
//            ]
//        ];
//
//        $return['pay_list'] = $pay_list;
//
//	    return $this->success($return);
//	}

    /**
     *
     * 下单确认页面初始化
     *
     * @param GoodsService $goodsService
     * @param StoreService $storeService
     * @return mixed
     */
	public function initByGoods(GoodsService $goodsService,StoreService $storeService,LogisticsService $logisticsService){

		$user_id = Input::get('user_id');
        $spec_id = Input::get('spec_id');//套装商品规格id
		$quantity = Input::get('quantity',1);
        $addr_id = Input::get('addr_id',0);//地址

		if (!$spec_id || !$quantity || !$user_id)
        {
            return $this->failure('参数不对');
        }

        $userinfo = DB::table('member')->where('user_id',$user_id)->first();
        if(!$userinfo){
            return $this->failure("用户不存在");
        }

        //TODO
//        if(empty($userinfo->user_name)){
//            return $this->need_bind();
//        }

	    /* 是否有商品 */
        $spec_info = $goodsService->getGoodsSpec($spec_id);

        if (!$spec_info){
            return $this->failure('商品不存在');
        }

        if ($quantity > $spec_info->stock){
            return $this->failure('库存不足');
        }

        //编辑商品规格信息
        $spec_1 = $spec_info->spec_name_1 ? $spec_info->spec_name_1 . ':' . $spec_info->spec_1 : $spec_info->spec_1;
        $spec_2 = $spec_info->spec_name_2 ? $spec_info->spec_name_2 . ':' . $spec_info->spec_2 : $spec_info->spec_2;

        if($spec_info->spec_name_1 && $spec_info->spec_name_2){
            $specification =  $spec_1 . ' ' . $spec_2;
        }elseif($spec_info->spec_name_1 && !$spec_info->spec_name_2 ){
            $specification =  $spec_1;
        }elseif($spec_info->spec_name_2 && !$spec_info->spec_name_1){
            $specification =  $spec_2;
        }else{
            $specification = "";
        }

//        $configs= json_decode($spec_info->config);
//        $config['shipping'] = (array)$configs->shipping;

        //编辑数据
        $temp = [
//            'store_info' => [
//                'store_id' => $spec_info->store_id,
//                'store_name' => $spec_info->store_name
//            ],
//            'total_store' => [
//                'goods_amount' => $spec_info->price*$quantity,
//                'quantity' => $quantity,
////                'shipping_fee_info' => "满".$config['shipping']['min_free']."元包邮,不足金额运费".$config['shipping']['shipping_fee']."元"
//            ],
//            'set_info' => [],
            'goods'=>[],
        ];

        //组合商品子商品数据
//        $subgoods = [];
//        if($spec_info->is_set){
//            $subgoods = $goodsService->getSubGoods2([$spec_info->goods_id]);
//            $temp['set_info']['goods_id'] = $spec_info->goods_id;
//            $temp['set_info']['goods_name'] = $spec_info->goods_name;
//            $temp['set_info']['spec_id'] = $spec_info->spec_id;
//            $temp['set_info']['specification'] = $specification ;
//
//            /* 商品缩略图 */
//            empty($spec_info->default_image) && $spec_info->default_image = env('default_goods_image');
//            $temp['set_info']['goods_image'] = complete_url($spec_info->default_image);
//
//            $temp['set_info']['quantity'] = $quantity;
//            $temp['set_info']['price'] = $spec_info->price;
//            $temp['set_info']['stock'] = $spec_info->stock;
//            foreach($subgoods as $k => $goods){
//                //规格信息编辑
//                $temp_spec_1 = $goods->spec_name_1 ? $goods->spec_name_1 . ':' . $goods->spec_1 : $goods->spec_1;
//                $temp_spec_2 = $goods->spec_name_2 ? $goods->spec_name_2 . ':' . $goods->spec_2 : $goods->spec_2;
//                $temp_specification = $temp_spec_1 . ' ' . $temp_spec_2;
//
//                $temp['goods'][$k]['goods_id'] = $goods->goods_id;
//                $temp['goods'][$k]['goods_name'] = $goods->goods_name;
//                $temp['goods'][$k]['spec_id'] = $goods->spec_id;
//                $temp['goods'][$k]['specification'] = $temp_specification;
//                $temp['goods'][$k]['quantity'] = $quantity;
//                $temp['goods'][$k]['price'] = $goods->price;
//                $temp['goods'][$k]['stock'] = $goods->stock;
//                /* 商品缩略图 */
//                empty($goods->default_image) && $goods->default_image = env('default_goods_image');
//                $temp['goods'][$k]['goods_image'] = complete_url($goods->default_image);
//            }
//        }else{
            $temp['goods'][0]['store_id'] = $spec_info->store_id;
            $temp['goods'][0]['goods_id'] = $spec_info->goods_id;
            $temp['goods'][0]['goods_name'] = $spec_info->goods_name;
            $temp['goods'][0]['spec_id'] = $spec_info->spec_id;
            $temp['goods'][0]['specification'] = $specification ;
            $temp['goods'][0]['quantity'] = $quantity;
            $temp['goods'][0]['price'] = $spec_info->price;
            $temp['goods'][0]['market_price'] = $spec_info->market_price;
            $temp['goods'][0]['stock'] = $spec_info->stock;
            /* 商品缩略图 */
//            empty($spec_info->default_image) && $spec_info->default_image = env('default_goods_image');
//            $temp['goods'][0]['goods_image'] = complete_url($spec_info->default_image);

            empty($spec_info->default_image) && $spec_info->default_image = env('default_goods_image');
            $temp['goods'][0]['goods_image'] = complete_url($spec_info->default_image);
//            dd($temp);

//        }

        //获取默认地址
        $address= null;
        if($addr_id){

            $address= DB::table('address')->where('user_id',$user_id)->where('addr_id',$addr_id)->first();
            $arr_str=explode(" ",$address->region_name);//以空格为拆分条件
            if(!empty($arr_str))
            {
                $region_id =  DB::table('region')->where('region_name',$arr_str[0])->value('region_id');
            }

            $postage = $logisticsService->getLogisticsMoney( $spec_info->goods_id,$region_id,$quantity);
        } else {
            $address= DB::table('address')->where('user_id',$user_id)->where('is_default',1)->first();
            if($address){
                $arr_str = explode(" ",$address->region_name);//以空格为拆分条件
                if(!empty($arr_str))
                {
                    $region_id =  DB::table('region')->where('region_name',$arr_str[0])->value('region_id');
                }
                $postage = $logisticsService->getLogisticsMoney( $spec_info->goods_id,$region_id,$quantity);
            }

        }

        //编辑返回值
        $return = $temp;

        if($address){
            $return['default_address'] = (array)$address;
        }else {
            $postage = $logisticsService->getLogisticsMoney( $spec_info->goods_id,0,$quantity);
            $return['default_address'] = [];

        }

//        /* 配送方式 */
//        $cashierService = new CashierService();
//        /* 默认配送方式 */
//        $shipping_methods = $cashierService->getShippingMethods($store_id);
//        $return['default_shipping']          = $shipping_methods;

//        /* 配送费用=首件费用＋超出的件数*续件费用 */
//        if($shipping_methods){
//            $shipping_fee = $shipping_methods->first_price + ($temp['total_store']['quantity'] - 1) * $shipping_methods->step_price;
//        }else{
//            $shipping_fee = 0;
//        }

        //获取店铺配置
//        $storeConfig = $storeService->getStoreConfig($spec_info->store_id);

        /* 配送费为固定设置 */
//        if($temp['total_store']['goods_amount'] < $storeConfig['shipping']['min_free']){
//            $shipping_fee = $storeConfig['shipping']['shipping_fee'];
//        }else{
            $shipping_fee = 0;
//        }
        $return['shipping_fee'] = $shipping_fee;

//        /* 默认使用快要过期的可用优惠券 */
//        $couponService = new CouponService();
//        $user_coupon = $couponService->getCashierCouponMethods($user_id,$temp['total_store']['goods_amount']);
//        $return['default_coupon'] = $user_coupon;
//        if($user_coupon){
//            $coupon_fee = $user_coupon['coupon_value'];
//        }else{
            $coupon_fee = 0;
//        }
        $return['postage'] = $postage;
        $return['sub_amount'] = $spec_info->price - $coupon_fee;

        return $this->success($return);
	}

//    public function initByPintuan(){
//
//        $user_id = Input::get('user_id');
//        $store_id = Input::get('store_id',1);
//
//        $spec_id = Input::get('spec_id');//拼团规格id
//
//        $pintuan_id = Input::get('pintuan_id'); //拼团id
//
//        $tuan_id = Input::get('tuan_id',0); //团id  开团默认0
//
//        $quantity = Input::get('quantity',1);
//
//        if (!$spec_id || !$quantity || !$pintuan_id )
//        {
//            return $this->failure('参数不对');
//        }
//
//        $userinfo = DB::table('member')->where('user_id',$user_id)->first();
//        if(!$userinfo){
//            return $this->failure("用户不存在");
//        }
//
//        if(empty($userinfo->user_name)){
//            return $this->need_bind();
//        }
//
//        $pintuanService = new PintuanService();
//
//        //检查是否可以开团或者参团
//        $returnCheck = $pintuanService->checkPintuan($pintuan_id,$tuan_id,$user_id);
//        if($returnCheck!= ""){
//            return $this->failure($returnCheck);
//        }
//
//        /* 是否有商品 */
//        $spec_info = $pintuanService->getPintuanSpec($spec_id);
//
//        if (!$spec_info){
//            return $this->failure('商品不存在');
//        }
//
//        if ($quantity > $spec_info->stock){
//            return $this->failure('库存不足');
//        }
//
//        if (($spec_info->max_per_user > 0) && ($quantity > $spec_info->max_per_user)){
//            return $this->failure('该商品每个人单次购买不可超过'.$spec_info->max_per_user.'件');
//        }
//
//        //编辑商品规格信息
//        $spec_1 = $spec_info->spec_name_1 ? $spec_info->spec_name_1 . ':' . $spec_info->spec_1 : $spec_info->spec_1;
//        $spec_2 = $spec_info->spec_name_2 ? $spec_info->spec_name_2 . ':' . $spec_info->spec_2 : $spec_info->spec_2;
//
//        if($spec_info->spec_name_1 && $spec_info->spec_name_2){
//            $specification = $spec_1 . ' ' . $spec_2;
//        }else{
//            $specification = '';
//        }
//
//        $configs= json_decode($spec_info->config);
//        $config['shipping'] = (array)$configs->shipping;
//
//        //编辑数据
//        $temp = [
////            'store_info' => [
////                'store_id' => $spec_info->store_id,
////                'store_name' => $spec_info->store_name
////            ],
//            'total_store' => [
//                'kinds' => 1,
//                'goods_amount' => $spec_info->price*$quantity,
//                'quantity' => $quantity,
//                'shipping_fee_info' => "满".$config['shipping']['min_free']."元包邮,不足金额运费".$config['shipping']['shipping_fee']."元"
//            ],
//            'goods'=>[],
//        ];
//
//        $temp['goods'][0]['pt_spec_id'] = $spec_info->pt_spec_id;
//        $temp['goods'][0]['goods_id'] = $spec_info->goods_id;
//        $temp['goods'][0]['goods_name'] = $spec_info->goods_name;
//        $temp['goods'][0]['spec_id'] = $spec_info->spec_id;
//        $temp['goods'][0]['specification'] = $specification ;
//        $temp['goods'][0]['quantity'] = $quantity;
//        $temp['goods'][0]['price'] = $spec_info->price;
//        $temp['goods'][0]['stock'] = $spec_info->stock;
//
//        /* 商品缩略图 */
////        empty($spec_info->default_image) && $spec_info->default_image = env('default_goods_image');
////        $temp['goods'][0]['goods_image'] = complete_url($spec_info->default_image);
//
//        empty($spec_info->default_image2) && $spec_info->default_image2 = env('default_goods_image');
//        $temp['goods'][0]['goods_image'] = complete_url($spec_info->default_image2);
//
//        //获取默认地址
//        $address= DB::table('address')->where('user_id',$user_id)->where('is_default',1)->first();
//
//        //编辑返回值
//        $return = $temp;
//
//        if($address){
//            $return['default_address'] = (array)$address;
//        }else {
//            $return['default_address'] = [];
//        }
//
////        /* 配送方式 */
////        $cashierService = new CashierService();
////        /* 默认配送方式 */
////        $shipping_methods = $cashierService->getShippingMethods($store_id);
////        $return['default_shipping']          = $shipping_methods;
//
////        /* 配送费用=首件费用＋超出的件数*续件费用 */
////        if($shipping_methods){
////            $shipping_fee = $shipping_methods->first_price + ($temp['total_store']['quantity'] - 1) * $shipping_methods->step_price;
////        }else{
////            $shipping_fee = 0;
////        }
//
//        /* 所有的拼团类的购买都是包邮的 */
//        //获取店铺配置
////        $storeService = new StoreService();
////        $storeConfig = $storeService->getStoreConfig($spec_info->store_id);
////
////        /* 配送费为固定设置 */
////        if($temp['total_store']['goods_amount'] < $storeConfig['shipping']['min_free']){
////            $shipping_fee = $storeConfig['shipping']['shipping_fee'];
////        }else{
////            $shipping_fee = 0;
////        }
//
//        $shipping_fee = 0;
//
//        $return['shipping_fee'] = $shipping_fee;
//
//        /* 默认使用快要过期的可用优惠券 */
//        $couponService = new CouponService();
//        $user_coupon = $couponService->getCashierCouponMethods($user_id,$temp['total_store']['goods_amount']);
//        $return['default_coupon'] = $user_coupon;
//        if($user_coupon){
//            $coupon_fee = $user_coupon['coupon_value'];
//        }else{
//            $coupon_fee = 0;
//        }
//
//        $return['sub_amount'] = $temp['total_store']['goods_amount'] + $shipping_fee - $coupon_fee;
//
//        //支付方式列表
//        $pay_list = [
//            [
//                'payment_id'   => 1,
//                'payment_name' => '支付宝',
//                'payment_code' => 'alipay'
//            ],
//            [
//                'payment_id'   => 2,
//                'payment_name' => '微信',
//                'payment_code' => 'wxPay'
//            ]
//        ];
//
//        $return['pay_list'] = $pay_list;
//
//        return $this->success($return);
//    }

//	public function createOrderByCart(){
//
//        //**参数验证**
//	    if(!Input::has('addr_id')){
//	        return $this->failure('请选择收货地址');
//	    }
//
////        if(!Input::has('shipping_id')){
////            return $this->failure('请选择配送方式');
////        }
//
//        if(!Input::has('tuan_id')){
//            return $this->failure('参数错误');
//        }
//
//        if(!Input::has('pintuan_id')){
//            return $this->failure('参数错误');
//        }
//
//        if(!Input::has('payment_id')){
//            return $this->failure('请选择支付方式');
//        }
//
//	    $addr_id = Input::get('addr_id');
//	    $user_id = Input::get('user_id');
//
//	    $userinfo = DB::table('member')->where('user_id',$user_id)->first();
//		if(!$userinfo){
//		    return $this->failure("用户不存在");
//		}
//
//        if(empty($userinfo->user_name)){
//            return $this->need_bind();
//        }
//
//        $address = Address::where('user_id',$user_id)
//            ->where('addr_id',$addr_id)->first();
//        if(!$address){
//            return $this->failure("地址无效，请重新选择或填写新地址");
//        }
//
//		$store_id = Input::get('store_id',1);
//		$storeinfo = DB::table('store')->where('store_id',$store_id)->get();
//		if(!$storeinfo){
//		    return $this->failure("店铺不存在");
//		}
//
//        //判断是否是全部购物车购买
//		if(!Input::has('rec_ids')){//全部购物车
//            $rec_id_list = [];
//	    }else{
//	    	$rec_id_list=explode(",",Input::get('rec_ids'));
//	    }
//
//        $goods = Input::get('goods','normal');
//        $orderService = new OrderService();
//        $goods_info = $orderService->getGoodsInfo($user_id,$rec_id_list,$store_id,$goods);
//
//        /* 购物车是空的 */
//        if ($goods_info === false)
//        {
//            return $this->failure('购物车是空的');
//        }
//
//        /*  检查库存 */
//        $goods_beyond = $orderService->checkBeyondStock($goods_info['items']);
//        if ($goods_beyond)
//        {
//            return $this->failure('库存不足',$goods_beyond);
//        }
//
//        /* 在此获取生成订单的两个基本要素：用户提交的数据（POST），商品信息（包含商品列表，商品总价，商品总数量，类型），所属店铺 */
//        $store_id = intval(Input::get('store_id',1));
//
//        DB::beginTransaction();
//
//        try {
//            /* 优惠券数据处理 */
//            $coupon_type = Input::get('coupon_type','coupon');
//            $coupon_sn = Input::get('coupon_sn',0);
//            if ($goods_info['allow_coupon'] && $coupon_type && $coupon_sn)
//            {
//                if(!in_array($coupon_type, array('coupon','cashcoupon'))){
//                    return $this->failure('参数不对');
//                }
//                $coupon_info = [];
//                if($coupon_type=='coupon') {
//                    $couponService = new CouponService();
//                    $coupon_info = $couponService->getCouponInfo($coupon_sn);
//                } /*else {
//                    $coupon_info = DB::table('cash_coupon_sn')->join('cash_coupon','cash_coupon_sn.coupon_id','=','cash_coupon.coupon_id')
//                        ->where('cash_coupon.store_id',$store_id)->where('cash_coupon_sn.coupon_sn',$coupon_sn)
//                        ->select('cash_coupon.*','cash_coupon_sn.remain_times')->first();
//                }   */
//
//
//                if (empty($coupon_info)){
//                    return $this->failure('无效的优惠券编号');
//                }
//
//                $coupon_info = $coupon_info->toArray();
//
//                if ($coupon_info['remain_times'] < 1){
//                    return $this->failure('该优惠券已被使用');
//                }
//                $time = gmtime();
//                if ($coupon_info['coupon']['start_time'] > $time){
//                    return $this->failure('该优惠券尚不能使用');
//                }
//
//                if ($coupon_info['coupon']['end_time'] < $time)
//                {
//                    return $this->failure('该优惠券已过期');
//                }
//                if ($coupon_info['coupon']['min_amount'] > $goods_info['amount'])
//                {
//                     return $this->failure('未达到使用金额');
//                }
//                unset($time);
//                $goods_info['discount'] = $coupon_info['coupon']['coupon_value'];
//                $goods_info['coupon_sn'] = $coupon_sn;
//            }
//
//            $order_sn = $orderService->getOrderSn();
//            /* 将这些信息传递给订单类型处理类生成订单(你根据我提供的信息生成一张订单) */
//            $submit = $orderService->submitOrder(array(
//                'goods_info'    =>  $goods_info,        //商品信息（包括列表，总价，总量，所属店铺，类型）,可靠的!
//                'post'          =>  Input::all(),       //用户填写的订单信息
//                'order_sn'      =>  $order_sn           //订单号
//
//            ));
//
//            if (!$submit['order_id'])
//            {
//                return $this->failure($submit['error']);
//            }
//
//            $order_id = $submit['order_id'];
//
//            /* 下单完成后清理商品，如清空购物车，或将团购拍卖的状态转为已下单之类的 */
//            $orderService->clearGoods($user_id,$rec_id_list,$goods);
//
//            //减去优惠券使用次数
//            DB::table('coupon_sn')->where('coupon_sn',$coupon_sn)->decrement('remain_times',1);
//
//            /* 更新下单次数 */
//            $goods_ids = array();
//            foreach ($goods_info['items'] as $goods)
//            {
//                $goods_ids[] = $goods['goods_id'];
//            }
//            DB::table('goods_statistics')->whereIn('goods_id',$goods_ids)->increment('orders');
//
//            DB::commit();
//
//            /* 获取订单信息 */
//            $order_info = DB::table('order')->where('order_id',$order_id)->where('buyer_id',$user_id)->first();
//            if (empty($order_info))
//            {
//                return $this->failure('没有该订单');
//            }
//            //订单商品信息
//            $order_goods = DB::table('order_goods')->where('order_id',$order_id)->get();
//            if(empty($order_goods)){
//            	return $this->failure('订单中没有商品');
//            }
//            $detail = '';
//            if(count($order_goods)>1){
//            	$order_name = '多商品购买';
//            	foreach($order_goods as $g){
//            		$detail .= $g->goods_name . '+';
//            	}
//            	$goods_detail = substr($detail, 0, -1);
//            }else{
//            	$ordergoods = current($order_goods);
//            	$order_name = $ordergoods->goods_name;
//            	$goods_detail = $ordergoods->goods_name;
//            }
//            $order_info->order_name = $order_name;
//            $order_info->goods_detail = $goods_detail;
//
//            /* 订单有效性判断 */
//            if ($order_info->payment_code != 'cod'
//                && $order_info->status != ORDER_PENDING
//                && $order_info->status != ORDER_ACCEPTED){
//                return $this->failure('订单不可支付');;
//            }
//
//            return $this->success($order_info);
//
//        } catch(\Exception $e){
//            DB::rollback();
//            throw $e;
//        }
//
//	}
	
	public function createOrderByGoods(){
	
	 	//**参数验证**
	    if(!Input::has('addr_id')){
	        return $this->failure('请选择收货地址');
	    }

//	    if(!Input::has('payment_id')){
//	        return $this->failure('请选择支付方式');
//	    }

//        if(!Input::has('shipping_id')){
//            return $this->failure('请选择配送方式');
//        }

        if(!Input::has('quantity')){
            return $this->failure('请选择购买数量');
        }

		$user_id = Input::get('user_id');
		$userinfo = DB::table('member')->where('user_id',$user_id)->first();
		if(!$userinfo){
		    return $this->failure("用户不存在");
		}

        //TODO 是否要绑定手机后才能使用
//        if(empty($userinfo->user_name)){
//            return $this->need_bind();
//        }

//		$store_id = Input::get('store_id');
//		$storeinfo = DB::table('store')->where('store_id',$store_id)->get();
//		if(!$storeinfo){
//		    return $this->failure("超市不存在");
//		}

		$spec_id = Input::get('spec_id');
        $quantity = Input::get('quantity');

        $orderService = new OrderService();
		$goods_info = $orderService->getSingleGoodsInfo($spec_id,$quantity);

        if ($goods_info === false)
        {
            /* 购物车是空的 */
            return $this->failure('商品已下架');
        }

        /*  检查库存 */
        $goods_beyond = $orderService->checkBeyondStock($goods_info['items']);

        if ($goods_beyond)
        {
            return $this->failure('库存不足',$goods_beyond);
        }

		/* 在此获取生成订单的两个基本要素：用户提交的数据（POST），商品信息（包含商品列表，商品总价，商品总数量，类型），所属店铺 */

        DB::beginTransaction();

        try {
            /* 优惠券数据处理 */
//            $coupon_type = Input::get('coupon_type','coupon');
//            $coupon_sn = Input::get('coupon_sn',0);
//            if ($goods_info['allow_coupon'] && $coupon_type && $coupon_sn)
//            {
//                if(!in_array($coupon_type, array('coupon','cashcoupon'))){
//                    return $this->failure('参数不对');
//                }
//                $coupon_info = [];
//                if($coupon_type=='coupon') {
//                    $couponService = new CouponService();
//                    $coupon_info = $couponService->getCouponInfo($coupon_sn);
//                } /*else {
//                    $coupon_info = DB::table('cash_coupon_sn')->join('cash_coupon','cash_coupon_sn.coupon_id','=','cash_coupon.coupon_id')
//                        ->where('cash_coupon.store_id',$store_id)->where('cash_coupon_sn.coupon_sn',$coupon_sn)
//                        ->select('cash_coupon.*','cash_coupon_sn.remain_times')->first();
//                }   */
//
//
//                if (empty($coupon_info)){
//                    return $this->failure('无效的优惠券编号');
//                }
//
//                $coupon_info = $coupon_info->toArray();
//
//                if ($coupon_info['remain_times'] < 1){
//                    return $this->failure('该优惠券已被使用');
//                }
//                $time = gmtime();
//                if ($coupon_info['coupon']['start_time'] > $time){
//                    return $this->failure('该优惠券尚不能使用');
//                }
//
//                if ($coupon_info['coupon']['end_time'] < $time)
//                {
//                    return $this->failure('该优惠券已过期');
//                }
//                if ($coupon_info['coupon']['min_amount'] > $goods_info['amount'])
//                {
//                    return $this->failure('未达到使用金额');
//                }
//                unset($time);
//                $goods_info['discount'] = $coupon_info['coupon']['coupon_value'];
//                $goods_info['coupon_sn'] = $coupon_sn;
//            }

            $order_sn = $orderService->getOrderSn();

            /* 将这些信息传递给订单类型处理类生成订单(你根据我提供的信息生成一张订单) */
            $submit = $orderService->submitOrder(array(
                'goods_info'    =>  $goods_info,        //商品信息（包括列表，总价，总量，所属店铺，类型）,可靠的!
                'post'          =>  Input::all(),       //用户填写的订单信息
                'order_sn'      =>  $order_sn           //订单号

            ));

            if (!$submit['order_id'])
            {
                DB::rollback();
                return $this->failure($submit['error']);
            }

            $order_id = $submit['order_id'];

            //减去优惠券使用次数
//            DB::table('coupon_sn')->where('coupon_sn',$coupon_sn)->decrement('remain_times',1);

            /* 更新下单次数 */
            $goods_ids = array();
            foreach ($goods_info['items'] as $goods)
            {
                $goods_ids[] = $goods['goods_id'];
            }

            DB::table('goods_statistics')->whereIn('goods_id',$goods_ids)->increment('orders');

            DB::commit();

            $order_info = DB::table('order')->where('order_id',$order_id)->where('buyer_id',$user_id)->get();
        	if (empty($order_info))
        	{
            	return $this->failure('没有该订单');
        	}

        	$order_info = current($order_info);

        	$order_goods = DB::table('order_goods')->where('order_id',$order_id)->get();

            if(empty($order_goods)){
            	return $this->failure('订单中没有商品');
            }

            $ordergoods = current($order_goods);
            $order_name = $ordergoods->goods_name;
            $goods_detail = $ordergoods->goods_name;

	        /* 订单有效性判断 */
//	        if ($order_info->payment_code != 'cod'
//                && $order_info->status !=ORDER_PENDING
//                && $order_info->status != ORDER_ACCEPTED){
//	            return $this->failure('订单不可支付');
//	        }

			$order_info->order_name = $order_name;
            $order_info->goods_detail = $goods_detail;

            return $this->success($order_info);

        } catch(\Exception $e){
            DB::rollback();
            throw $e;
        }

	}

//    public function createOrderByPintuan(){
//        //**参数验证**
//        if(!Input::has('addr_id')){
//            return $this->failure('请选择收货地址');
//        }
//
//        if(!Input::has('payment_id')){
//            return $this->failure('请选择支付方式');
//        }
//
//        if(!Input::has('quantity')){
//            return $this->failure('请选择购买数量');
//        }
//
//        $pintuan_id = Input::get('pintuan_id');//拼团id
//        $tuan_id = Input::get('tuan_id',0);//团id
//
//        $user_id = Input::get('user_id');
//        $userinfo = DB::table('member')->where('user_id',$user_id)->first();
//        if(!$userinfo){
//            return $this->failure("用户不存在");
//        }
//
//        if(empty($userinfo->user_name)){
//            return $this->need_bind();
//        }
//
//        $store_id = Input::get('store_id');
//        $storeinfo = DB::table('store')->where('store_id',$store_id)->get();
//        if(!$storeinfo){
//            return $this->failure("超市不存在");
//        }
//
//        $spec_id = Input::get('spec_id');
//        $quantity = Input::get('quantity',1);
//
//        $pintuanService = new PintuanService();
//
//        //检查是否可以开团或者参团
//        $returnCheck = $pintuanService->checkPintuan($pintuan_id,$tuan_id,$user_id);
//        if($returnCheck!= ""){
//            return $this->failure($returnCheck);
//        }
//
//        /* 是否有商品 */
//        $spec_info = $pintuanService->getPintuanSpec($spec_id);
//
//        $orderService = new OrderService();
//        $goods_info = $orderService->getPintuanGoodsInfo($spec_info->pintuan_type,$spec_id,$quantity,$store_id);
//
//        if ($goods_info['quantity'] > $spec_info->stock){
//            return $this->failure('库存不足');
//        }
//
//        if (($spec_info->max_per_user > 0) && ($goods_info['quantity'] > $spec_info->max_per_user)){
//            return $this->failure('该商品每个人单次购买不可超过'.$spec_info->max_per_user.'件');
//        }
//
//        /*  检查库存 */
//        $goods_beyond = $orderService->checkBeyondStock($goods_info['items']);
//
//        if ($goods_beyond)
//        {
//            return $this->failure('库存不足',$goods_beyond);
//        }
//
//        /* 在此获取生成订单的两个基本要素：用户提交的数据（POST），商品信息（包含商品列表，商品总价，商品总数量，类型），所属店铺 */
//
//        DB::beginTransaction();
//
//        try {
//            /* 优惠券数据处理 */
//            $coupon_type = Input::get('coupon_type','coupon');
//            $coupon_sn = Input::get('coupon_sn',0);
//            if ($goods_info['allow_coupon'] && $coupon_type && $coupon_sn)
//            {
//                if(!in_array($coupon_type, array('coupon','cashcoupon'))){
//                    return $this->failure('参数不对');
//                }
//                $coupon_info = [];
//                if($coupon_type=='coupon') {
//                    $couponService = new CouponService();
//                    $coupon_info = $couponService->getCouponInfo($coupon_sn);
//                } /*else {
//                    $coupon_info = DB::table('cash_coupon_sn')->join('cash_coupon','cash_coupon_sn.coupon_id','=','cash_coupon.coupon_id')
//                        ->where('cash_coupon.store_id',$store_id)->where('cash_coupon_sn.coupon_sn',$coupon_sn)
//                        ->select('cash_coupon.*','cash_coupon_sn.remain_times')->first();
//                }   */
//
//
//                if (empty($coupon_info)){
//                    return $this->failure('无效的优惠券编号');
//                }
//
//                $coupon_info = $coupon_info->toArray();
//
//                if ($coupon_info['remain_times'] < 1){
//                    return $this->failure('该优惠券已被使用');
//                }
//                $time = gmtime();
//                if ($coupon_info['coupon']['start_time'] > $time){
//                    return $this->failure('该优惠券尚不能使用');
//                }
//
//                if ($coupon_info['coupon']['end_time'] < $time)
//                {
//                    return $this->failure('该优惠券已过期');
//                }
//                if ($coupon_info['coupon']['min_amount'] > $goods_info['amount'])
//                {
//                    return $this->failure('未达到使用金额');
//                }
//                unset($time);
//                $goods_info['discount'] = $coupon_info['coupon']['coupon_value'];
//                $goods_info['coupon_sn'] = $coupon_sn;
//            }
//
//            $order_sn = $orderService->getOrderSn();
//
//            /* 将这些信息传递给订单类型处理类生成订单(你根据我提供的信息生成一张订单) */
//            $submit = $orderService->submitOrder(array(
//                'goods_info'    =>  $goods_info,        //商品信息（包括列表，总价，总量，所属店铺，类型）,可靠的!
//                'post'          =>  Input::all(),       //用户填写的订单信息
//                'order_sn'      =>  $order_sn           //订单号
//
//            ));
//
//            if (!$submit['order_id'])
//            {
//                return $this->failure($submit['error']);
//            }
//
//            $order_id = $submit['order_id'];
//
////            //@TODO 已经放到支付回调中，等待测试 测试通过删除代码
////            //添加团信息
////            $pintuanService->createOrEnterTuan($pintuan_id,$user_id,$order_id,$tuan_id,$quantity);
//
//            //减去优惠券使用次数
//            DB::table('coupon_sn')->where('coupon_sn',$coupon_sn)->decrement('remain_times',1);
//
//            /* 更新下单次数 */
//            $goods_ids = array();
//            foreach ($goods_info['items'] as $goods)
//            {
//                $goods_ids[] = $goods['goods_id'];
//            }
//
//            DB::table('goods_statistics')->whereIn('goods_id',$goods_ids)->increment('orders');
//
//            DB::table('pintuan_statistics')->where('pintuan_id',$pintuan_id)->increment('orders');
//
//            DB::commit();
//
//            $order_info = DB::table('order')->where('order_id',$order_id)->where('buyer_id',$user_id)->get();
//            if (empty($order_info))
//            {
//                return $this->failure('没有该订单');
//            }
//
//            $order_info = current($order_info);
//
//            $order_goods = DB::table('order_goods')->where('order_id',$order_id)->get();
//
//            if(empty($order_goods)){
//                return $this->failure('订单中没有商品');
//            }
//
//            $ordergoods = current($order_goods);
//            $order_name = $ordergoods->goods_name;
//            $goods_detail = $ordergoods->goods_name;
//
//            /* 订单有效性判断 */
//            if ($order_info->payment_code != 'cod'
//                && $order_info->status !=ORDER_PENDING
//                && $order_info->status != ORDER_ACCEPTED){
//                return $this->failure('订单不可支付');;
//            }
//
//            $order_info->order_name = $order_name;
//            $order_info->goods_detail = $goods_detail;
//
//            return $this->success($order_info);
//
//        } catch(Exception $e){
//            DB::rollback();
//            throw $e;
//        }
//
//    }

    /**
     * 确认支付
     * @param $user_id
     * @param $order_id
     * @param OrderService $orderService
     * @param OrderPingppService $orderPingppService
     * @return mixed
     */
    public function gotoPay($user_id,$order_id,OrderService $orderService,OrderPingppService $orderPingppService)
    {
        //支付类型
        $pay_channel = Input::get('pay_channel','');

        //是否需要全部的返回数据
        $needs_full = Input::get('needs_full',0);

        if(!$user_id){
            return $this->failure('请先登录');
        }

        if (!$order_id)
        {
            return $this->failure('未找到订单');
        }

        if (!$pay_channel)
        {
            return $this->failure('请选择支付方式');
        }

        $order_info  =  $orderService->getOrderInfo($user_id,$order_id);

        if (empty($order_info))
        {
            return $this->failure('未找到订单');
        }

    	/* 订单有效性判断 */
        if ($order_info->status != ORDER_PENDING)
        {
            return $this->failure('该订单不可支付');
        }

        if($order_info->buyer_id != $user_id ){
            return $this->failure('无权操作该订单');
        }

        //如果库存不足，则支付失败
        foreach($order_info->orderGoods as $item){
            if($item->quantity > $item->goodsSpec->stock){
                return $this->failure('库存不足，无法支付，请重新下单');
            }
        }

        $checkChennelData = $orderPingppService->checkChennel($pay_channel);
        if(!$checkChennelData['result']){
            return $this->failure($checkChennelData['msg']);
        }

        $channel = $checkChennelData['data'];

        //获取支付para
        $payparaData = $orderPingppService->getPayPara($user_id,$order_id,$order_info->seller_name,$order_info->order_sn,$order_info->order_amount,$pay_channel,$needs_full);
        if(!$payparaData['result']){
            return $this->failure($payparaData['msg']);
        }

        /* 保存支付方式 */

        $order_info->payment_id = $channel->payment_id;
        $order_info->payment_code = $channel->payment_code;
        $order_info->payment_name = $channel->payment_name;

        $order_info->save();

        return $this->success($payparaData['data']);
    }

}
